package com.xywy.me;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.wjk.WjkFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 验证码：修改手机号 - 验证码
 * 
 * @author xiaogd
 * 
 */
public class SetupValdateCodeActivity extends BaseActivity {
	private static final String TAG = "SetupValdateCodeActivity";
	private String mobileStr = "";
	private Button btnNext;
	private TextView valTs;
	private TextView tvMObile;
	JSONObject msgBack;
	MyProgress myProgress;
	EditText etValCode;

	private TextView timer;
	private Context mContext;
	private MyTimer mc;
	private TextView newGet;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.me_setup_val_code);
		this.preInit();
		this.initView();
		this.loadData();

	}

	public void startOnClick(View view) {
		switch (view.getId()) {
		case R.id.btn_me_setup_valcode_next:
			bindNext();
			break;
		case R.id.tv_me_setup_pwd_timer_newget:
			mc.start();
			// 是否是当前页重新获取验证码
			newGetCode = true;
			sendMsg();
			break;

		}
		;
	}

	private void bindNext() {
		// 发送网络请求
		this.sendMsg();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	public void initView() {
		// title
		TitleBar2 titleBar = (TitleBar2) findViewById(R.id.me_setup_val_cdoe_title_bar);
		TextView tvTitle = titleBar.getTitle();
		titleBar.getGo().setVisibility(View.INVISIBLE);
		titleBar.onClickBack(this);
		btnNext = (Button) findViewById(R.id.btn_me_setup_valcode_next);
		valTs = (TextView) findViewById(R.id.tv_me_setup_valcode_ts);

		tvMObile = (TextView) findViewById(R.id.tv_me_setup_valpwd_number);
		tvMObile.setText(mobileStr);

		etValCode = (EditText) findViewById(R.id.et_setup_ac_val_mobile);
		timer = (TextView) findViewById(R.id.tv_val_pwd_timer);
		newGet = (TextView) findViewById(R.id.tv_val_pwd_timer_newget);

		String ts = getString(R.string.tv_start_valpwd_ts);
		// 控件赋值
		Spannable span = new SpannableString(ts);
		span.setSpan(
				new ForegroundColorSpan(mContext.getResources().getColor(
						R.color.start_bt_bg)), 6, 9,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		valTs.setText(span);
		tvTitle.setText(getString(R.string.tv_start_valcode_qr));

		myProgress = new MyProgress(this, 10);

		// 启动倒计时
		mc = new MyTimer(60000, 1000);
		mc.start();
	}

	@Override
	public void preInit() {
		this.mContext = this.context;
		mobileStr = getIntent().getStringExtra("mobile");
	}

	@Override
	public void loadData() {

	}


	String userid = "";
	/**
	 * 返回
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			try {
				msgBack = new JSONObject(msg.obj.toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (msg.arg1 == ResultCode.SUCCESS) {
				Intent intent = new Intent(mContext, FragmentMainActivity.class);
				mContext.startActivity(intent);
				finish();
				if (newGetCode) { // 是否为当前页重新获取 难证码
					return;
				} else {
					saveMobile();
				}
			} else if (msg.arg1 == ResultCode.PWDERROR502
					|| msg.arg1 == ResultCode.PWDERROR503) {
				Toast.makeText(mContext, msgBack.optString("error"),
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, getString(R.string.common_fail),
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	/**
	 * 将 新手机号 存入本地
	 */
	private void saveMobile() {
		userid = msgBack.optString("userid");
		MLog.i(TAG, "当前人的userid:" + userid);
		SharedPreferences sp = mContext.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("mobile", mobileStr);
		editor.putString("password", "null");
		editor.commit();
	}

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	// 异步加载
	private AsyncHttpClient asyncHttpClient;
	// 是否是当前页重新获取验证码
	private boolean newGetCode = false;

	// 处理网络请求
	public void sendMsg() {
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.verifyCode);
		// 请求方式
		paramsParser.request = "get";

		// 请求参数
		params.put("target", mobileStr);
		params.put("code", etValCode.getText().toString());
		// AHDSG
		String id = getIntent().getExtras().getString("id");
		params.put("id", id);

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = this.context;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			handler.sendMessage(message);
		}
	};

	/**
	 * 定义一个倒计时的内部类
	 */
	class MyTimer extends CountDownTimer {
		public MyTimer(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			timer.setText(30 + "");
			newGet.setVisibility(View.VISIBLE);
			timer.setTextColor(getResources().getColor(
					R.color.wjk_xsdf_share_btn));
			timer.setClickable(true);
			timer.setFocusable(true);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			timer.setText(millisUntilFinished / 1000 + "");
			timer.setTextColor(getResources().getColor(
					R.color.wjk_xsdf_share_btn_ap));
			timer.setClickable(false);
			timer.setFocusable(false);
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mc.cancel();
		super.onDestroy();
	}
}
